import hashlib
import time

from rest_framework.permissions import BasePermission

from config.settings.base import WORKFLOWTOKEN


class ApiPermissionCheck(BasePermission):

    @classmethod
    def has_permission(self, request, view):
        """
        token permission check
        """

        signature = request.META.get('HTTP_SIGNATURE')
        timestamp = request.META.get('HTTP_TIMESTAMP')

        return self.signature_check(timestamp, signature)

    @classmethod
    def signature_check(cls, timestamp: str, signature: str):
        """
        signature check
        :param timestamp:
        :param signature:
        :return:
        """
        ori_str = timestamp + WORKFLOWTOKEN
        tar_str = hashlib.md5(ori_str.encode(encoding='utf-8')).hexdigest()
        if tar_str == signature:
            time_now_int = int(time.time())
            if abs(time_now_int - int(timestamp)) <= 120:
                return True
            else:
                return False
        else:
            return False

